import os
from datetime import datetime
import hashlib

# Get the current time and format it
current_time = datetime.now().strftime('%Y%m%d%H%M%S')

print(current_time)

dir_10800 = "tran_files" # 需打包的文件存放路径
file_type='63' # 文件类型 03：S 0d：J 63:Y
file_prefix='Y' # 文件名前缀 S 单程票 J 交通部 Y 一卡通

def loop_dir():
    long_str_head = file_type + current_time + '010400010000000001' 
    long_str = ''
    len = 0
    file_name = file_prefix + '.04000100.' + current_time + '.000001'
    for path in os.listdir(dir_10800):
        # 解析文件
        path_file = dir_10800 + '/' + path
        with open(path_file, 'rb') as file:
            content = file.read()
        hex_str = content.hex()

        # print(hex_str)
        if path.startswith(file_prefix):
            # print(hex_str[46 + 42:60 + 42]) #交易时间
            # print(hex_str[94 + 42:102 + 42]) #设备编码
            long_str += hex_str[42:-32]
            len += int(hex_str[34:42],16)
    
    # print(long_str_head)
    # print(f"{len:08X}".lower())   
    # print(long_str)

    all_str = long_str_head + f"{len:08X}".lower() + long_str

    binary_data = bytes.fromhex(all_str)
    md5_hash = hashlib.md5(binary_data).hexdigest()
    all_str = all_str + md5_hash
    
    # print(all_str)
    # print(md5_hash)

    with open(file_name, 'wb') as f:
        f.write(bytes.fromhex(all_str))

loop_dir()